package com.maker.ai.config;

import com.maker.ai.aiservice.MakerChatService;
import com.maker.ai.service.OptRagService;
import com.maker.ai.tool.DateTool;
import com.maker.ai.tool.EmailTool;
import com.maker.ai.tool.ReservationTool;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.parser.apache.tika.ApacheTikaDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolProvider;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class CommonConfig {
    @Resource
    private OpenAiChatModel model;
    @Resource
    private ChatMemoryStore redisChatMemoryStore;
    @Resource
    private EmbeddingModel embeddingModel;
    @Resource
    private EmbeddingStore<TextSegment>  embeddingStore;
    @Resource
    private McpToolProvider mcpToolProvider; //// MCP 工具
    @Resource
    private ReservationTool reservationTool;     // 本地 Spring Tool
    @Resource
    private DateTool dateTool;
    @Resource
    private EmailTool emailTool;

    @Resource
    private OpenAiStreamingChatModel openAiStreamingChatModel;

//    @Bean
//    public ChatService chatService(){
//
//        ChatService  chatService = AiServices.builder(ChatService.class).chatModel(model).build();
//        return chatService;
//    }
    //公共记忆的
    @Bean
    public ChatMemory chatMemory(){

        MessageWindowChatMemory memory = MessageWindowChatMemory.builder()
                .maxMessages(20)
                .build();
        return memory;
    }
    //私有的记忆ID
    @Bean
    public ChatMemoryProvider chatMemoryProvider(){
        ChatMemoryProvider  chatMemoryProvider =   new ChatMemoryProvider(){
            @Override
            public ChatMemory get(Object memoryId) {

                return MessageWindowChatMemory.builder()
                        .id(memoryId)
                        .maxMessages(20)
                        .chatMemoryStore(redisChatMemoryStore)
                        .build();
            }
        };
        return chatMemoryProvider;
    }

    //构建向量数据库操作对象
//    @Bean
//    public EmbeddingStore store() {
//        try {
//            //加载文档到内存  西北大学.md
////        List<Document> documents = ClassPathDocumentLoader.loadDocuments("content");
//            List<Document> documents = FileSystemDocumentLoader.loadDocuments("D:\\java_project\\langchain-demo\\src\\main\\resources\\content\\", new ApacheTikaDocumentParser());
//            if (documents == null) {
//                throw new RuntimeException("没有需要初始化的知识库");
//            } else {
//                //构建向量数据库操作对象
////        InMemoryEmbeddingStore store = new InMemoryEmbeddingStore();
//                //构建文档分割器对象
//                DocumentSplitter documentSplitter = DocumentSplitters.recursive(1000, 50);
//                //实现文本数据切割，向量化，存储
//                EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder()
////                .embeddingStore(store)
//                        .embeddingStore(embeddingStore)
//                        .documentSplitter(documentSplitter)
//                        .embeddingModel(embeddingModel)
//                        .build();
//                ingestor.ingest(documents);
////        return store;
//                return embeddingStore;
//            }
//        } catch (Exception e) {
//            System.err.println("文档加载或处理过程中出现错误: " + e.getMessage());
//            e.printStackTrace();
//            throw new RuntimeException("初始化知识库失败", e);
//        }
//    }


    //构建数据库检索对象
    @Bean
    public ContentRetriever contentRetriever(/*EmbeddingStore store**/){
        return EmbeddingStoreContentRetriever.builder()
//                .embeddingStore(store)
                .embeddingStore(embeddingStore)
                .maxResults(3)
                .minScore(0.5)
                .embeddingModel(embeddingModel)
                .build();
    }


    @Bean
    public MakerChatService mcpChatService(
            ChatMemoryProvider chatMemoryProvider,
            ContentRetriever contentRetriever
    ) {
        // 2. 一并注入 AiServices
        return AiServices.builder(MakerChatService.class)
                .streamingChatModel(openAiStreamingChatModel)
                .chatMemoryProvider(chatMemoryProvider)
                .contentRetriever(contentRetriever) // <-- 这里也带上
                .toolProvider(mcpToolProvider)
                .tools(reservationTool,dateTool,emailTool)
                .build();
    }







}
